package cn.lanchengkeji.datafillingsystem.service.impl;



import cn.lanchengkeji.datafillingsystem.common.Const;
import cn.lanchengkeji.datafillingsystem.common.ResponseBean;
import cn.lanchengkeji.datafillingsystem.common.StatusCode;
import cn.lanchengkeji.datafillingsystem.entity.Roles;
import cn.lanchengkeji.datafillingsystem.entity.RolesPrivilege;
import cn.lanchengkeji.datafillingsystem.entity.UserRole;
import cn.lanchengkeji.datafillingsystem.mapper.RolesMapper;
import cn.lanchengkeji.datafillingsystem.service.IOperationService;
import cn.lanchengkeji.datafillingsystem.service.IRolesPrivilegeService;
import cn.lanchengkeji.datafillingsystem.service.IRolesService;
import cn.lanchengkeji.datafillingsystem.service.IUserRoleService;
import cn.lanchengkeji.datafillingsystem.utils.Utils;
import cn.lanchengkeji.datafillingsystem.vo.RolesVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author Yixu
 * @since 2018-11-29
 */
@Service
public class RolesServiceImpl extends ServiceImpl<RolesMapper, Roles> implements IRolesService {
    @Resource
    private IRolesPrivilegeService iRolesPrivilegeService;

    @Resource
    private IUserRoleService iUserRoleService;

    @Resource
    private IOperationService iOperationService;

    // 获取已添加的角色
    @Override
    public List<Roles> getRolesByUser(Integer userId) {
        return baseMapper.selectByUser(userId);
    }

    // 获取未添加的角色
    @Override
    public List<Roles> getWtjRolesByUser(Integer userId) {
        return baseMapper.selectWtjByUser(userId);
    }

    /**
     * 查询单条
     *
     * @param condition
     * @return
     * @author yuhao 2018-12-06 17:15
     */
    @Override
    public Roles selectOneRoles(Roles condition) {
        if (Utils.isEmpty(condition) || Utils.isEmpty(condition.getId())) {
            return null;
        }

        return this.getById(condition);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param condition
     * @return
     * @author yuhao 2018-12-06 17:15
     */
    @Override
    public Page<RolesVO> pageRoles(Page<RolesVO> page, RolesVO condition) {

        List<RolesVO> rolesList = baseMapper.findRoles(page, condition);
        for (RolesVO oneRole : rolesList) {
            // 查询该角色对应的操作权限
            oneRole.setOperationList(iOperationService.selectOperationsByRoleId(oneRole.getId()));
        }
        page.setRecords(rolesList);
        return page;
    }

    /**
     * 添加角色：同时添加菜单权限、相关用户、操作权限
     *
     * @param roles
     * @return
     * @throws Exception
     * @author yuhao 2018-12-07 11:45
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public ResponseBean insertRoles(RolesVO roles) throws Exception {
        if (Utils.isEmpty(roles)) {
            return new ResponseBean(StatusCode.IS_NULL, roles);
        }

        List<Roles> searchRoles;

        // 判断角色名称是否重复
        if (Utils.notEmpty(roles.getRoleName())) {
            QueryWrapper<Roles> condition = new QueryWrapper<>();
            condition.eq(Roles.ROLE_NAME, roles.getRoleName());
            searchRoles = this.list(condition);
            if (searchRoles.size() > 0) {
                return new ResponseBean(StatusCode.ROLE_NAME_REPEAT, roles);
            }
        }

        if (this.save(roles)) {

            // 添加菜单权限、相关用户、操作权限
            List<RolesPrivilege> rolesPrivileges = new ArrayList<>();
            List<UserRole> userRoles = new ArrayList<>();

            // 菜单权限
            if (Utils.notEmpty(roles.getMenuIdList())) {
                List<Integer> menuIds = roles.getMenuIdList();
                for (Integer id : menuIds) {
                    RolesPrivilege nRolesPrivilege = new RolesPrivilege();
                    nRolesPrivilege.setPrivilegeType(Const.PRIVILEGE_TYPE_MENU);
                    nRolesPrivilege.setRolesId(roles.getId());
                    nRolesPrivilege.setRefId(id);
                    rolesPrivileges.add(nRolesPrivilege);
                }
            }

            // 操作权限
            if (Utils.notEmpty(roles.getOperationIdList())) {
                List<Integer> operationIds = roles.getOperationIdList();
                for (Integer id : operationIds) {
                    RolesPrivilege nRolesPrivilege = new RolesPrivilege();
                    nRolesPrivilege.setPrivilegeType(Const.PRIVILEGE_TYPE_OPERATION);
                    nRolesPrivilege.setRolesId(roles.getId());
                    nRolesPrivilege.setRefId(id);
                    rolesPrivileges.add(nRolesPrivilege);
                }
            }

            // 用户
            if (Utils.notEmpty(roles.getUserIdList()) && roles.getUserIdList().size() > 0) {
                List<Integer> userIds = roles.getUserIdList();
                for (Integer id : userIds) {
                    UserRole nUserRole = new UserRole();
                    nUserRole.setUserId(id);
                    nUserRole.setRoleId(roles.getId());
                    userRoles.add(nUserRole);
                }
            }

            // 批量插入roles_privilege
            if (rolesPrivileges.size() > 0) {
                iRolesPrivilegeService.saveBatch((Collection) rolesPrivileges);
            }
            // 批量插入user_role
            if (rolesPrivileges.size() > 0) {
                iUserRoleService.saveBatch((Collection) userRoles);
            }
        }
        return new ResponseBean(StatusCode.OK, roles);
    }

    /**
     * 修改角色：同时修改菜单权限、相关用户、操作权限
     *
     * @param roles
     * @return
     * @throws Exception
     * @author yuhao 2018-12-07 11:46
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public ResponseBean updateRoles(RolesVO roles) throws Exception {
        if (Utils.isEmpty(roles) || Utils.isEmpty(roles.getId())) {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }
        Roles oRoles = this.getById(roles.getId());
        if (Utils.isEmpty(oRoles)) {
            return new ResponseBean(StatusCode.ROLE_NOT_FOUND, null);
        }

        List<Roles> searchRoles;

        // 判断除自己外角色名称是否重复
        if (Utils.notEmpty(roles.getRoleName())) {
            QueryWrapper<Roles> condition = new QueryWrapper<>();
            condition.eq(Roles.ROLE_NAME, roles.getRoleName()).ne("id", roles.getId());
            searchRoles = this.list(condition);
            if (searchRoles.size() > 0) {
                return new ResponseBean(StatusCode.ROLE_NAME_REPEAT, roles);
            }
        }

        if (this.saveOrUpdate(roles)) {

            // 先删除菜单权限、相关用户、操作权限，再批量添加菜单权限、相关用户、操作权限
            List<RolesPrivilege> rolesPrivileges = new ArrayList<>();

            // 菜单权限
            if (Utils.notEmpty(roles.getMenuIdList())) {
                List<Integer> menuIds = roles.getMenuIdList();
                for (Integer id : menuIds) {
                    RolesPrivilege nRolesPrivilege = new RolesPrivilege();
                    nRolesPrivilege.setPrivilegeType(Const.PRIVILEGE_TYPE_MENU);
                    nRolesPrivilege.setRolesId(roles.getId());
                    nRolesPrivilege.setRefId(id);
                    rolesPrivileges.add(nRolesPrivilege);
                }
            }

            // 操作权限
            if (Utils.notEmpty(roles.getOperationIdList())) {
                List<Integer> operationIds = roles.getOperationIdList();
                for (Integer id : operationIds) {
                    RolesPrivilege nRolesPrivilege = new RolesPrivilege();
                    nRolesPrivilege.setPrivilegeType(Const.PRIVILEGE_TYPE_OPERATION);
                    nRolesPrivilege.setRolesId(roles.getId());
                    nRolesPrivilege.setRefId(id);
                    rolesPrivileges.add(nRolesPrivilege);
                }
            }

            // 按照roleId,批量删除roles_privilege和user_role
            Map<String, Object> privilegeMap = new HashMap<>();
            privilegeMap.put(RolesPrivilege.ROLES_ID, roles.getId());
            boolean delSuccess = iRolesPrivilegeService.removeByMap(privilegeMap);

            // 批量插入roles_privilege
            if (delSuccess && rolesPrivileges.size() > 0) {
                iRolesPrivilegeService.saveBatch(rolesPrivileges);
            }
        }
        return new ResponseBean(StatusCode.OK, roles);
    }

    /**
     * 删除角色：如果有菜单权限、相关用户、操作权限，不能删，否则可删
     *
     * @param roles
     * @return
     * @throws Exception
     * @author yuhao 2018-12-07 11:47
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public ResponseBean deleteRoles(RolesVO roles) throws Exception {

        // 参数不存在
        if (Utils.isEmpty(roles) || Utils.isEmpty(roles.getId())) {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }

        // 判断当前角色是否存在
        Roles oRoles = this.getById(roles.getId());
        if(Utils.isEmpty(oRoles)){
            return new ResponseBean(StatusCode.ROLE_NOT_FOUND,null);
        }

        // 判断该角色是否有用户、是否有操作权限
        if(iRolesPrivilegeService.getByRoleId(roles.getId()).size()>0){
            return new ResponseBean(StatusCode.ROLE_EXIST_MENU,roles);
        }
        if(iUserRoleService.getByRoleId(roles.getId()).size()>0){
            return new ResponseBean(StatusCode.ROLE_EXIST_USER,roles);
        }

        // 删除角色
        this.removeById(roles.getId());

        // 批量删除user_role  批量删除roles_privilege
        Map<String, Object> privilegeMap = new HashMap<>();
        privilegeMap.put(RolesPrivilege.ROLES_ID, roles.getId());
        iRolesPrivilegeService.removeByMap(privilegeMap);

        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put(UserRole.ROLE_ID, roles.getId());
        iUserRoleService.removeByMap(roleMap);

        return new ResponseBean(StatusCode.OK,roles);
    }
}
